package com.lzy.arithmetic;

/**
 * Author: lzy
 * Date:   2020/06/09 11:51
 * Description:
 **/
public class 两数相加 {

    public static void main(String[] args) {
        ListNode l1 = new ListNode(1);
        // l1.next = new ListNode(4);
        // l1.next.next = new ListNode(3);

        ListNode l2 = new ListNode(9);
        l2.next = new ListNode(9);
        // l2.next.next = new ListNode(4);

        ListNode result = addTwoNumbers(l1, l2);
        while (result != null) {
            System.out.println(result.val);
            result = result.next;
        }
    }


    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //结果链表
        ListNode result = new ListNode(0);
        ListNode oldResult = result;
        //进位
        int carry = 0;

        while (l1 != null || l2 != null || carry != 0) {
            int l1_num = 0;
            if (l1 != null) {
                l1_num = l1.val;
                l1 = l1.next;
            }

            int l2_num = 0;
            if (l2 != null) {
                l2_num = l2.val;
                l2 = l2.next;
            }
            // 每位相加
            int sum = l1_num + l2_num + carry;
            // 每位结果
            int num = sum % 10;
            // 进位更新
            carry = sum / 10;
            // 节点赋值
            result.next = new ListNode(num);
            // 节点右移
            result = result.next;
        }
        return oldResult.next;
    }

}

